#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>

int insert_data(MYSQL mysql, char *cc, int num)
{
	char *query = NULL;
	int ret;
	query = (char *)malloc(sizeof(char)*50);
	sprintf(query, "insert into first values('', '%s', '%d')", cc, num);
	/*插入，成功则返回0*/  
	ret = mysql_real_query(&mysql, query, (unsigned int)strlen(query));  
	if(query != NULL){
		free(query);
		query = NULL;
	}
	return ret;
}

int delete_data(MYSQL mysql, int num)
{
	char *query = NULL;
	int ret;
	query = (char *)malloc(sizeof(char)*50);
	sprintf(query, "delete from first where ID='%d'", num);
	/*删除，成功则返回0*/
	ret = mysql_real_query(&mysql, query, (unsigned int)strlen(query));
	if(query != NULL){
		free(query);
		query = NULL;
	}
	return ret;
}

int select_data(MYSQL mysql, char *tables)
{
	MYSQL_RES *res;
	MYSQL_ROW row;
	char *query = NULL;
	int ret,t;
	query = (char *)malloc(sizeof(char)*50);
	sprintf(query ,"select * from %s", tables);
	/*查询，成功则返回0*/
	ret = mysql_real_query(&mysql, query, (unsigned int)strlen(query));
	if(ret) {
		printf("Query failed!\n");
	}else {
		printf("command [%s] ...\n", query);
	}
	/*mysql_store_result将全部的查询结果读取到客户端*/
	res = mysql_store_result(&mysql);

	/*mysql_fetch_row检索结果集的下一行,没有结果返回NULL*/
	while(row = mysql_fetch_row(res)) {
		/*mysql_num_fields返回结果集合中的字段数目*/
		for(t=0; t<mysql_num_fields(res); t++)
		{
			printf("%s\t", row[t]);
		}
		printf("\n");
	}

	if(query != NULL){
		free(query);
		query = NULL;
	}
	return ret;
}

int main()
{
	MYSQL mysql;
	char *query;
	int ret;
	/*连接之前，先用mysql_init初始化MYSQL连接句柄*/
	mysql_init(&mysql);
	/*使用mysql_real_connect连接服务器,其参数依次为MYSQL句柄，服务器IP地址，
	登录mysql的用户名，密码，要连接的数据库等*/
	if(!mysql_real_connect(&mysql, "192.168.1.103", "day961", "19910426q", "test", 0, NULL, 0)) {
		printf("Error connecting to Mysql!\n\n");
		mysql_close(&mysql);
		return 0;
	}else {
		printf("Connected Mysql successful!\n\n");
	}
	
	/*插入*/
	ret = insert_data(mysql, "neten", 999);
	if(ret) {  
		printf("Insert data failure! %d\n", ret);
	}else {
		printf("Insert data success! %d\n", ret); 
	}
	/*删除*/
	ret = delete_data(mysql, 10);
	if(ret) {
		printf("Delete data failure! %d\n", ret);
	}else {
		printf("Delete data success! %d\n", ret);
	}

	/*查询*/
	ret = select_data(mysql, "first");
/*	if(ret) {
		printf("Query failed!\n");
	}else {
		printf("command [%s] ...\n", query);
	}
*/
	/*关闭连接*/
	mysql_close(&mysql);
	return 0;
}
